<template>
    <div class="page-wrapper">
        <BreadMenu />
        <div style="height:96%; background:#fff; padding:var(--mPadding); ">
            <div style="display:flex; align-items:center; justify-content: space-between; margin-bottom:var(--mPadding);">
                <div style="width:10vw;"><FlexDatePicker :data="{ paramKey:'searchTime', clearable:false,  type:'month' }" :form="form" /></div>
                <div style="display:flex; justify-content: flex-end;">
                    <div class="flex-btn opacity" @click="handleExport">
			            <img :src="Icon" />
                        <span>导出</span>
			        </div>
                </div>  
            </div>         
            <el-scrollbar height="94%">
                <TableWrapper
                    :hasControls="false" 
                    :sourceData="tableData" 
                    :column="column"
                    :hasBorder="true" 
                    :hasPagination="false" 
                    :noPadding="true" 
                    :combineMethod="handleCombine"
                    :cellStyle="setCellStyle"
                    emptyText="暂无巡检历史"
                />
                <TableWrapper
                    :hasControls="false" 
                    :sourceData="correctionList" 
                    :column="column2" 
                    :hasBorder="true" 
                    :hasPagination="false"
                    :noPadding="true" 
                    :combineMethod="handleCombine2"
                    emptyText="暂无整改记录"
                    @row-click="handleRowClick"
                />
            </el-scrollbar>
            
        </div>   
	</div> 
</template>

<script setup>
    import { watch, ref, reactive, onMounted, h } from 'vue';
    import { useRoute, useRouter } from 'vue-router';
    import { getMultiInspections } from '@/api/object.js';
    import { getTaskInspection, getTaskResult } from '@/api/task.js'; 
    import BreadMenu from '@/components/BreadMenu.vue';
    import { ElMessage, ElLoading } from 'element-plus';
	import TableWrapper from '@/components/TableWrapper/index.vue';
    import { createSheet, downloadExcel } from '@/utils/excel.js';
    import FlexDatePicker from '@/components/FlexDatePicker.vue';
    import { formatDateTime } from '@/utils/date';
    import Icon from '@/assets/icon-export.png';
    const router = useRouter();
    const route = useRoute();
    const ids = ref([]);
    const tableData = ref([]);
    const correctionList = ref([]);

    const date = new Date();
    date.setDate(1);
    const form = reactive({
        'searchTime':date
    })
    const merges = [];
    const merges2 = [];
    const column = ref([
        { label:'巡检对象', prop:'targetName', width:'10%'},
        { label:'巡检项名称', width:'10%', prop:'itemName' },
        { label:'标准与要求', prop:'itemNormAndDemand', width:'12%' }, 
        { label:'检查方法及工具', prop:'checkWayAndTool', width:'8%' },
        { label:'巡检周期', prop:'cycleName', width:'6%' },
        // 1待处理;0不通过(需整改);3通过"  
        { label:'巡检结果', className:'align', children:[] }
    ]); 	
    
    const column2 = [
        { label:'', width:'5%', hasTpl:true, render:row=>({ com:h('span', null, '整改记录'), val:'整改记录' })},
        { label:'记录时间', width:'10%', hasTpl:true, render:row=>{ 
            let str = row.createTime ? row.createTime.replace('T', ' ').slice(0, row.createTime.length - 3): '--';
            return { com:h('div', null, str), val:str };
        }},
        { label:'巡检对象', prop:'targetName', width:'10%'},
        { label:'巡检项名称', prop:'itemName', width:'16%' },
        { label:'问题描述', prop:'problemDescription', width:'24%' },
        { label:'巡检人',  width:'5%', prop:'inspectionUser' },
        { label:'处理时间', width:'10%', hasTpl:true, render:row=>{ 
            let str = row.rectifyTime ? row.rectifyTime.replace('T', ' ').slice(0, row.rectifyTime.length - 3): '--';
            return { com:h('div', null, str), val:str }
        }},
        { label:'处理结果', width:'10%', prop:'rectifyExplanation'},
        { label:'处理人', width:'5%', prop:'rectifyUser' }
    ]
    function handleCombine({ row, column, rowIndex, columnIndex }){
        // console.log('row...', row);
        // console.log('column...', column);
        // console.log('rowIndex...', rowIndex);
        // console.log('columnIndex...', columnIndex);
        if ( columnIndex === 0 ) {
            if ( row.isStartRow ) {
                let obj = {
                    rowspan:row.childNum,
                    colspan:1
                }
                merges.push({ ...obj, rowIndex, columnIndex });
                return obj;
            } else {
                return {
                    rowspan:0,
                    colspan:0
                }
            }
        } 
        if ( row.specKey ){
            if ( columnIndex === 1 ) { 
                let obj = {
                    rowspan:1,
                    colspan:3
                }    
                merges.push({ ...obj, rowIndex, columnIndex });       
                return obj;
            } else if ( columnIndex === 2 || columnIndex === 3  ){
                return { rowspan:0, colspan:0 }
            }
        } 
    }  
    function setCellStyle({ row, column, rowIndex, columnIndex }){
        if ( row.specKey ) {
            if ( columnIndex === 1 ) {
                return { textAlign:'center', color:'#000', fontWeight:'bold' }
            }
        } 
    }
    function handleCombine2({ row, column, rowIndex, columnIndex }){
        if ( columnIndex === 0 ) {
            if ( rowIndex === 0 ) {
                let obj = {
                    rowspan:correctionList.value.length,
                    colspan:1
                }
                merges2.push({ ...obj, rowIndex, columnIndex });     
                return obj;
            } else {
                return { rowspan:0, colspan:0 }
            }
        }
    }
    function handleRowClick(row){
        
    }
    function handleExport(){  
        if ( tableData.value.length ) {
            downloadExcel([
                { raw:createSheet(column.value, tableData.value, merges), sheetName:'历史巡检结果' }, 
                { raw:createSheet(column2, correctionList.value, merges2), sheetName:'整改记录' }
            ], '巡检结果和整改记录' );
        } else {
            ElMessage({
                type:'info',
                message:'数据源为空'
            })
        }
    }
    watch(()=>form.searchTime, ()=>{
        // console.log('time...', form.searchTime);
        fetchInspectionHistory();
    })
    const fetchInspectionHistory = ()=>{
        const loading = ElLoading.service({
  		    lock: true,
  		    text: 'Loading',
  		    background: 'rgba(0, 0, 0, 0.7)',
  		})
        getMultiInspections({ targetIds:ids.value.map(i=>i.i), searchTime:formatDateTime(form.searchTime, false) + ' 00:00:00' })
        .then(res=>{
			if ( res.data.code === 200 ){
                let arr = [];
                let pos = 0;
                ids.value.forEach(item=>{
                    let itemData = res.data.data[item.n] || [];
                    itemData.forEach((listItem, j)=>{
                        let obj = { ...listItem }
                        if ( j === 0 ) {
                            obj.isStartRow = true;
                            obj.childNum = itemData.length + 1
                        }
                        ++pos;
                        arr.push(obj)
                    })
                    arr.push({ cycleName:'巡检人', specKey:'actionUser', itemName:'说明：巡检正常 “√”、异常 “×”' });

                })
                // console.log(arr);
                let dateColumns = [];
                let actionUser = arr[0].inspectionUser;
                if ( arr && arr.length ) {
                    dateColumns = arr[0].timeDataList.map((item, index)=>({
                        label:String(index + 1), 
                        prop:index, 
                        width:'1%', 
                        className:'noPadding',
                        hasTpl:true,
                        render:(row, j)=>{
                            let str = '', childArr = [];
                            if ( row.specKey ) {
                                str = actionUser;
                                if ( actionUser ) {
                                    let sliceStr = arr[0].inspectionUser.slice(0,5);
                                    for(let k = 0; k < sliceStr.length; k++){
                                        childArr.push(h('div', null, sliceStr[k]));
                                    }
                                }
                            } else {
                                const temp = row.timeDataList && row.timeDataList[index] ? row.timeDataList[index]['checkResult'] : null;
                                str = temp && typeof temp === 'number' ? Number(temp) === 3 ? '√' : '×' : '';
                            }   
                            return { com:h('div', row.specKey ? { class:'vertical'} : null , row.specKey ? childArr : str), val:str };                                           
                        }
                    }))
                }
                column.value[5].children = dateColumns;
                tableData.value = arr;
                if ( res.data.data['整改登记'] ) {
                    correctionList.value = res.data.data['整改登记'];
                }
			}
		})
        .finally(()=>{
            loading.close();
        })
	};
   
    onMounted(()=>{
        if ( route.query.ids ) {
            let temp = JSON.parse(route.query.ids);
            if ( temp && temp.length ) {
                ids.value = temp;
            }
            fetchInspectionHistory();
        }
    })
</script>
